<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<input 
				v-model="searchKeyword" 
				class="search-input"
				placeholder="搜索蓝牙设备名称" 
				@confirm="searchDevices"
				@input="handleSearchInput"
			/>
			<button class="clear-btn" @tap="clearSearch" v-if="searchKeyword">×</button>
		</view>
		
		<!-- 操作按钮区域 -->
		<view class="action-buttons">
			<button class="scan-btn" @tap="startScan" :disabled="isScanning">
				{{ isScanning ? '扫描中...' : '开始扫描' }}
			</button>
			<button class="stop-btn" @tap="stopScan" :disabled="!isScanning">
				停止扫描
			</button>
		</view>
		
		<!-- 设备列表 -->
		<scroll-view class="device-list" scroll-y>
			<view class="section-title">附近蓝牙设备 ({{ filteredDevices.length }})</view>
			<view 
				v-for="device in filteredDevices" 
				:key="device.deviceId" 
				class="device-item"
			>
				<view class="device-info">
					<text class="device-name">{{ device.name || '未知设备' }}</text>
					<text class="device-id">{{ device.deviceId }}</text>
					<text class="device-rssi">信号强度: {{ device.RSSI }} dBm</text>
				</view>
				<button 
					class="connect-btn" 
					@tap="connectDevice(device)"
					:disabled="connectedDevices.some(d => d.deviceId === device.deviceId)"
				>
					{{ connectedDevices.some(d => d.deviceId === device.deviceId) ? '已连接' : '连接' }}
				</button>
			</view>
			
			<!-- 已连接设备 -->
			<view class="section-title" v-if="connectedDevices.length > 0">
				已连接设备 ({{ connectedDevices.length }})
			</view>
			<view 
				v-for="device in connectedDevices" 
				:key="device.deviceId" 
				class="device-item connected"
			>
				<view class="device-info">
					<text class="device-name">{{ device.name || '未知设备' }}</text>
					<text class="device-id">{{ device.deviceId }}</text>
					<text class="device-status">已连接</text>
				</view>
				<button class="disconnect-btn" @tap="disconnectDevice(device)">
					断开
				</button>
			</view>
		</scroll-view>
		
		<!-- 配对弹窗 -->
		<view class="modal" v-if="showPairModal">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">蓝牙配对</text>
					<button class="close-btn" @tap="cancelPair">×</button>
				</view>
				<view class="modal-body">
					<input 
						v-model="pairCode" 
						class="pair-input"
						placeholder="请输入配对码"
						type="text"
					/>
				</view>
				<view class="modal-footer">
					<button class="cancel-btn" @tap="cancelPair">取消</button>
					<button class="confirm-btn" @tap="confirmPair">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isScanning: false,
				searchKeyword: '',
				devices: [],
				connectedDevices: [],
				currentPairDevice: null,
				pairCode: '',
				showPairModal: false
			}
		},
		
		computed: {
			filteredDevices() {
				if (!this.searchKeyword) {
					return this.devices
				}
				return this.devices.filter(device => 
					device.name && device.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
				)
			}
		},
		
		onLoad() {
			this.initBluetooth()
			this.loadConnectedDevices()
			this.setupGlobalEvents()
		},
		
		onShow() {
			this.loadConnectedDevices()
		},
		
		onUnload() {
			this.stopScan()
		},
		
		methods: {
			// 初始化蓝牙适配器
			async initBluetooth() {
				try {
					// 检查蓝牙适配器是否可用
					const systemInfo = uni.getSystemInfoSync()
					console.log('系统信息:', systemInfo)
					console.log('蓝牙适配器初始化成功')
				} catch (error) {
					console.error('蓝牙适配器初始化失败:', error)
					uni.showToast({
						title: '蓝牙初始化失败',
						icon: 'none'
					})
				}
			},
			
			// 开始扫描蓝牙设备
			async startScan() {
				try {
					// 检查蓝牙适配器是否可用
					const res = await uni.openBluetoothAdapter()
					console.log('蓝牙适配器打开成功')
					
					this.isScanning = true
					this.devices = []
					
					// 开始扫描
					uni.startBluetoothDevicesDiscovery({
						services: [],
						allowDuplicatesKey: false,
						interval: 0,
						success: (res) => {
							console.log('开始扫描蓝牙设备')
							uni.showToast({
								title: '开始扫描设备',
								icon: 'none'
							})
						},
						fail: (err) => {
							console.error('扫描失败:', err)
							uni.showToast({
								title: '扫描失败',
								icon: 'none'
							})
							this.isScanning = false
						}
					})
					
					// 监听发现新设备事件
					uni.onBluetoothDeviceFound((res) => {
						const devices = res.devices
						if (devices && devices.length > 0) {
							devices.forEach(device => {
								// 过滤掉已存在的设备
								if (!this.devices.some(d => d.deviceId === device.deviceId)) {
									this.devices.push({
										deviceId: device.deviceId,
										name: device.name,
										RSSI: device.RSSI || 0,
										advertisData: device.advertisData,
										localName: device.localName
									})
								}
							})
						}
					})
					
				} catch (error) {
					console.error('扫描错误:', error)
					uni.showToast({
						title: '请检查蓝牙权限',
						icon: 'none'
					})
					this.isScanning = false
				}
			},
			
			// 停止扫描
			stopScan() {
				if (this.isScanning) {
					uni.stopBluetoothDevicesDiscovery({
						success: (res) => {
							console.log('停止扫描')
							this.isScanning = false
							uni.offBluetoothDeviceFound() // 取消监听
						}
					})
				}
			},
			
			// 连接设备
			async connectDevice(device) {
				this.currentPairDevice = device
				
				// 检查设备是否已连接
				const connectedDevices = await this.getConnectedDevices()
				console.log('已连接设备:', connectedDevices)
				if (connectedDevices.some(d => d.deviceId === device.deviceId)) {
					uni.showToast({
						title: '设备已连接',
						icon: 'none'
					})
					return
				}
				
				// 打开配对弹窗
				this.showPairModal = true
				this.pairCode = ''
			},
			
			// 确认配对
			async confirmPair() {
				if (!this.pairCode) {
					uni.showToast({
						title: '请输入配对码',
						icon: 'none'
					})
					return
				}
				
				try {
					uni.showLoading({
						title: '连接中...'
					})
					
					// 创建蓝牙连接
					await uni.createBLEConnection({
						deviceId: this.currentPairDevice.deviceId,
						timeout: 10000
					})
					
					// 连接成功
					uni.hideLoading()
					uni.showToast({
						title: '连接成功',
						icon: 'success'
					})
					
					// 添加到已连接设备列表
					this.connectedDevices.push(this.currentPairDevice)
					
					// 保存到本地存储
					this.saveConnectedDevices()
					
					// 添加到历史记录
					this.addToHistory(this.currentPairDevice)
					
					// 更新扫描统计
					this.updateScanStats()
					
					// 关闭弹窗
					this.showPairModal = false
					this.currentPairDevice = null
					this.pairCode = ''
					
				} catch (error) {
					console.error('连接失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '连接失败',
						icon: 'none'
					})
				}
			},
			
			// 取消配对
			cancelPair() {
				this.currentPairDevice = null
				this.pairCode = ''
				this.showPairModal = false
			},
			
			// 断开设备连接
			async disconnectDevice(device) {
				try {
					uni.showLoading({
						title: '断开中...'
					})
					
					await uni.closeBLEConnection({
						deviceId: device.deviceId
					})
					
					// 从已连接设备列表中移除
					this.connectedDevices = this.connectedDevices.filter(
						d => d.deviceId !== device.deviceId
					)
					
					// 更新本地存储
					this.saveConnectedDevices()
					
					uni.hideLoading()
					uni.showToast({
						title: '已断开连接',
						icon: 'success'
					})
					
				} catch (error) {
					console.error('断开连接失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '断开失败',
						icon: 'none'
					})
				}
			},
			
			// 获取已连接的设备
			async getConnectedDevices() {
				try {
					const res = await uni.getConnectedBluetoothDevices({
						services: []
					})
					return res.devices || []
				} catch (error) {
					console.error('获取已连接设备失败:', error)
					return []
				}
			},
			
			// 保存已连接设备到本地存储
			saveConnectedDevices() {
				try {
					uni.setStorageSync('connectedDevices', this.connectedDevices)
				} catch (error) {
					console.error('保存设备列表失败:', error)
				}
			},
			
			// 从本地存储加载已连接设备
			loadConnectedDevices() {
				try {
					const devices = uni.getStorageSync('connectedDevices')
					if (devices) {
						this.connectedDevices = devices
					}
				} catch (error) {
					console.error('加载设备列表失败:', error)
				}
			},
			
			// 搜索设备
			searchDevices() {
				// 搜索逻辑已在computed中实现
				console.log('搜索关键词:', this.searchKeyword)
			},
			
			// 处理搜索输入
			handleSearchInput() {
				// 实时搜索
			},
			
			// 清空搜索
			clearSearch() {
				this.searchKeyword = ''
			},
			
			// 设置全局事件监听
			setupGlobalEvents() {
				// 监听来自个人中心页面的连接请求
				uni.$on('connectDevice', (device) => {
					this.connectDevice(device)
				})
			},
			
			// 更新扫描统计
			updateScanStats() {
				try {
					const stats = uni.getStorageSync('scanStats') || {}
					stats.totalScanned = (stats.totalScanned || 0) + 1
					uni.setStorageSync('scanStats', stats)
				} catch (error) {
					console.error('更新扫描统计失败:', error)
				}
			},
			
			// 添加到历史记录
			addToHistory(device) {
				try {
					let history = uni.getStorageSync('historyDevices') || []
					
					// 移除已存在的记录
					history = history.filter(d => d.deviceId !== device.deviceId)
					
					// 添加新记录
					history.unshift({
						...device,
						lastConnectTime: new Date().getTime()
					})
					
					// 限制历史记录数量
					if (history.length > 50) {
						history = history.slice(0, 50)
					}
					
					uni.setStorageSync('historyDevices', history)
					
				} catch (error) {
					console.error('保存历史记录失败:', error)
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		height: 100vh;
		background-color: #f5f5f5;
	}
	
	.search-bar {
		margin-bottom: 20rpx;
	}
	
	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}
	
	.scan-btn, .stop-btn {
		flex: 1;
		background-color: #007aff;
		color: white;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
	
	.scan-btn:disabled, .stop-btn:disabled {
		background-color: #cccccc;
	}
	
	.stop-btn {
		background-color: #ff3b30;
	}
	
	.device-list {
		height: calc(100vh - 200rpx);
	}
	
	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin: 20rpx 0;
		padding-left: 20rpx;
	}
	
	.device-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background: white;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 15rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.device-item.connected {
		border-left: 8rpx solid #4cd964;
	}
	
	.device-info {
		flex: 1;
	}
	
	.device-name {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.device-id {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 5rpx;
	}
	
	.device-rssi, .device-status {
		display: block;
		font-size: 24rpx;
		color: #999;
	}
	
	.connect-btn, .disconnect-btn {
		background-color: #4cd964;
		color: white;
		border-radius: 8rpx;
		font-size: 24rpx;
		padding: 15rpx 25rpx;
	}
	
	.connect-btn:disabled {
		background-color: #cccccc;
	}
	
	.disconnect-btn {
		background-color: #ff3b30;
	}
	
	/* 搜索栏样式 */
	.search-bar {
		position: relative;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.search-input {
		flex: 1;
		height: 70rpx;
		padding: 0 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 35rpx;
		background-color: white;
		font-size: 28rpx;
	}
	
	.clear-btn {
		position: absolute;
		right: 10rpx;
		width: 50rpx;
		height: 50rpx;
		background: transparent;
		border: none;
		font-size: 36rpx;
		color: #999;
	}
	
	/* 弹窗样式 */
	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}
	
	.modal-content {
		background: white;
		border-radius: 20rpx;
		width: 600rpx;
		max-width: 90vw;
		overflow: hidden;
	}
	
	.modal-header {
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.close-btn {
		background: transparent;
		border: none;
		font-size: 40rpx;
		color: #999;
	}
	
	.modal-body {
		padding: 30rpx;
	}
	
	.pair-input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}
	
	.modal-footer {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}
	
	.cancel-btn, .confirm-btn {
		padding: 15rpx 30rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
	
	.cancel-btn {
		background-color: #f0f0f0;
		color: #666;
	}
	
	.confirm-btn {
		background-color: #007aff;
		color: white;
	}
</style>